package file.iobase;

import java.io.*;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @Author 史祥连
 * @Date 2023/11/16 17:04
 * @Version 1.0
 */
public class WriteHelper {
    private BufferedWriter bw;

    public void buildBw(String file) {
        try {
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public void writeLine(String str, boolean writeNewLine) {
        try {
            bw.write(str);
            if (writeNewLine) {
                bw.newLine();
            }
            bw.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private WriteHelper() {
    }

    public static WriteHelper getWriteHelper(String filePath) {
        WriteHelper writeHelper = new WriteHelper();
        File file = new File(filePath);

        if (!file.exists()) {
            String[] split = filePath.split("\\\\");
            String path = Arrays.stream(split).limit(split.length-1).collect(Collectors.joining("\\"));
            try {
                boolean mkdirs = new File(path).mkdirs();

                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        writeHelper.buildBw(filePath);
        return writeHelper;
    }
}
